#include "terrain_Surface.h"

#include "../Logger/Logger.h"

namespace terrain {

Surface::Surface()
{
}

Surface::~Surface()
{
    //dtor
}

void Surface::Init(int rows, int columns, int patchSize)
{
    vector3f position;
    vector3f normal (0.0, 1.0, 0.0);

    Vertex *terrVertex = 0;

    for (int i = 0; i < (rows + 1); i++)
    {
        for (int j = 0; j < (columns + 1); j++)
        {
            position.X = j * patchSize;
            position.Z = i * patchSize;
            position.Y = 0;

            terrVertex = new Vertex;
            terrVertex->SetPosition (position);
            terrVertex->SetNormal (normal);

            m_Vertexes.push_back (terrVertex);
        }
    }

    Patch *terrPatch = 0;

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            terrPatch = new Patch;
            int topLeftIndex = j + i * (columns+1);

            terrPatch->SetTopL (m_Vertexes[topLeftIndex]);
            terrPatch->SetTopR (m_Vertexes[topLeftIndex + 1]);
            terrPatch->SetBotR (m_Vertexes[topLeftIndex + columns + 1 + 1]);
            terrPatch->SetBotL (m_Vertexes[topLeftIndex + columns + 1]);

            m_Patches.push_back (terrPatch);
        }
    }
}

void Surface::Destroy()
{
    for (size_t i = 0; i < m_Vertexes.size(); i++)
        delete m_Vertexes[i];
    for (size_t i = 0; i < m_Patches.size(); i++)
        delete m_Patches[i];
}

void Surface::Render (Renderer *renderer)
{
    renderer->PrepareSurface();

    for (size_t i = 0; i < m_Patches.size(); i++)
    {
        renderer->DrawSurfacePatch (m_Patches[i]);
    }
}


}
